<template>
  <div class="table-container">
    <!-- 筛选表单 -->
    <el-form :model="filters" inline>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="报关单号">
            <el-input v-model="filters.customsDeclarationNumber" placeholder="请输入报关单号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="提运单号">
            <el-input v-model="filters.billOfLadingNumber" placeholder="请输入提运单号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="消费使用单位">
            <el-input v-model="filters.consumptionUnit" placeholder="请输入消费使用单位"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="申报单位">
            <el-input v-model="filters.declarationUnit" placeholder="请输入申报单位"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="申报日期">
            <el-date-picker v-model="filters.declarationDate" type="date" placeholder="选择申报日期"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="进口日期&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;">
            <el-date-picker v-model="filters.importDate" type="date" placeholder="选择进口日期"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="商品名称">
            <el-input v-model="filters.selectedProductName" placeholder="请输入商品名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="商品编码">
            <el-input v-model="filters.productCode" placeholder="请输入商品编码" ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="境内收货人&nbsp;&nbsp;&nbsp;">
            <el-input v-model="filters.domesticConsignee" placeholder="请输入境内收货人"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="16">
          <!-- 空的占位符 -->
        </el-col>
        <el-col :span="8">
          <el-form-item>
            <el-button type="primary" @click="handleFilter">筛选</el-button>
            <el-button @click="resetFilter">重置</el-button>
            <el-button type="primary" @click="showAddDialog">新增</el-button>
            <el-button @click="showImportDialog">导入</el-button>
            <el-button type="primary" @click="showExport">导出</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 表格 -->
    <el-table :data="filteredData" style="width: 100%">
      <el-table-column prop="declarationDate" label="申报日期" width="100"></el-table-column>
      <el-table-column prop="importDate" label="进口日期" width="100"></el-table-column>
      <el-table-column prop="customsDeclarationNumber" label="报关单号" width="150"></el-table-column>
      <el-table-column prop="billOfLadingNumber" label="提运单号" width="150"></el-table-column>
      <el-table-column prop="consumptionUnit" label="消费使用单位" width="150"></el-table-column>
      <el-table-column prop="domesticConsignee" label="境内收货人" width="150"></el-table-column>
      <el-table-column prop="declarationUnit" label="申报单位" width="150"></el-table-column>
      <el-table-column label="商品名称" width="150">
        <template v-slot="scope">
          <el-select 
            v-model="scope.row.selectedProductName" 
            placeholder="请选择商品名称" 
            @change="handleProductNameChange(scope.row)"
            filterable
          >
            <el-option
              v-for="product in scope.row.products" 
              :key="product.productCode"
              :label="product.productName"
              :value="product.productName"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="productCode" label="商品编码" width="150"></el-table-column>
      <el-table-column label="操作" width="465">
        <template v-slot="scope">
          <el-button @click="showDetailsDialog(scope.row)" type="primary" size="small">详情</el-button>
          <el-button @click="showEditDialog(scope.row)" type="warning" size="small">修改</el-button>
          <el-button @click="showPaymentDialog(scope.row)" type="primary" size="small">付汇</el-button>
          <el-button @click="showGenerateDialog(scope.row)" type="primary" size="small">生成文件</el-button>
          <el-button @click="showDeleteDialog(scope.row)" type="danger" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 导出弹窗 -->
    <el-dialog v-model="exportVisible" title="导出选项" width="900">
      <Export />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="exportVisible = false">取消</el-button>
          <el-button type="primary" @click="exportVisible = false">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog v-model="detailsVisible" title="详情" top="5vh" width="80%">
      <Detail :row="selectedRow" :visible="detailsVisible" />
    </el-dialog>

    <!-- 修改弹窗 -->
    <el-dialog v-model="editVisible" title="修改" width="500">
      <p>修改内容</p>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editVisible = false">取消</el-button>
          <el-button type="primary" @click="editVisible = false">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 付汇弹窗 -->
    <el-dialog v-model="paymentVisible" title="付汇" width="500">
      <p>付汇内容</p>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="paymentVisible = false">取消</el-button>
          <el-button type="primary" @click="paymentVisible = false">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 生成文件弹窗 -->
    <el-dialog v-model="generateVisible" title="生成文件" width="600">
      <el-button type="primary" @click="generateVisible = false">生成发票(单抬头)</el-button>
      <el-button type="primary" @click="generateVisible = false">生成发票(双抬头)</el-button>
      <el-button type="primary" @click="generateVisible = false">生成合同(单抬头)</el-button>
      <el-button type="primary" @click="generateVisible = false">生成合同(双抬头)</el-button>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="generateVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 删除弹窗 -->
    <el-dialog v-model="deleteVisible" title="删除" width="500">
      <p>确定要删除吗?</p>
      <template #footer>
        <div class="dialog-footer centered-buttons">
          <el-button @click="deleteVisible = false">取消</el-button>
          <el-button type="primary" @click="deleteVisible = false">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增弹窗 -->
    <el-dialog v-model="addVisible" title="新增" width="500">
      <p>新增内容</p>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addVisible = false">取消</el-button>
          <el-button type="primary" @click="addVisible = false">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入弹窗 -->
    <ImportDialog v-model="importVisible" />
  </div>
</template>

<script>
import { ref, computed,onMounted } from 'vue';
import axios from 'axios';
import Export from './export.vue';
import ImportDialog from './ImportDialog.vue';
import Detail from './Detail.vue';

export default {
  props: {
    tableData: {
      type: Array,
      required: true,
    },
    filters: {
      type: Object,
      required: true,
    },
  },
  components: {
    Export,
    ImportDialog,
    Detail,
  },
  setup(props) {
    const exportVisible = ref(false);
    const detailsVisible = ref(false);
    const editVisible = ref(false);
    const paymentVisible = ref(false);
    const generateVisible = ref(false);
    const deleteVisible = ref(false);
    const addVisible = ref(false);
    const importVisible = ref(false);
    const selectedRow = ref(null);

    const initializeDefaultValues = () => {
      props.tableData.forEach(row => {
        if (row.products && row.products.length > 0) {
          const defaultProduct = row.products.find(product => product.id === 1);
          if (defaultProduct) {
            row.selectedProductName = defaultProduct.productName;
            row.productCode = defaultProduct.productCode;
          } else {
            row.selectedProductName = row.products[0].productName;
            row.productCode = row.products[0].productCode;
          }
        }
      });
    };
    onMounted(() => {
      initializeDefaultValues();
    });
    const handleProductNameChange = (row) => {
      const selectedProduct = row.products.find(item => item.productName === row.selectedProductName);
      if (selectedProduct) {
        row.productCode = selectedProduct.productCode;
      } else {
        row.productCode = '';
      }
    };

    const handleFilter = () => {
      console.log('当前筛选条件:', props.filters);
      // 触发筛选逻辑
    };

    const resetFilter = () => {
      Object.keys(props.filters).forEach(key => {
        props.filters[key] = '';
      });
    };

    const formatDate = (date) => {
      if (!date) return '';
      const d = new Date(date);
      const month = '' + (d.getMonth() + 1);
      const day = '' + d.getDate();
      const year = d.getFullYear();

      return [year, month.padStart(2, '0'), day.padStart(2, '0')].join('-');
    };

    const filteredData = computed(() => {
      return props.tableData.filter(item => {
        return Object.keys(props.filters).every(key => {
          if (!props.filters[key]) return true;
          if (key === 'declarationDate' || key === 'importDate') {
            const formattedDate = formatDate(props.filters[key]);
            return item[key] && item[key].startsWith(formattedDate);
          }
          return item[key] && item[key].includes(props.filters[key]);
        });
      });
    });

    const handleEdit = (row) => {
      this.$emit('edit', row);
    };

    const handleDelete = (row) => {
      this.$emit('delete', row);
    };

    const showExport = () => {
      exportVisible.value = true;
    };

    const showDetailsDialog = async (row) => {
      try {
        const response = await axios.get(`http://111.229.78.177:8000/api/customs.Declaration/detail?app_id=10001&number=${row.customsDeclarationNumber}`);
        if (response.data.code === 200) {
          selectedRow.value = response.data.data;
          detailsVisible.value = true;
        } else {
          console.error('Failed to fetch details:', response.data.message);
        }
      } catch (error) {
        console.error('Error fetching details:', error);
      }
    };

    const showEditDialog = (row) => {
      editVisible.value = true;
    };

    const showPaymentDialog = (row) => {
      paymentVisible.value = true;
    };

    const showGenerateDialog = (row) => {
      generateVisible.value = true;
    };

    const showDeleteDialog = (row) => {
      deleteVisible.value = true;
    };

    const showAddDialog = () => {
      addVisible.value = true;
    };

    const showImportDialog = () => {
      importVisible.value = true;
    };

    return {
      exportVisible,
      detailsVisible,
      editVisible,
      paymentVisible,
      generateVisible,
      deleteVisible,
      addVisible,
      importVisible,
      selectedRow,
      filteredData,
      handleProductNameChange,
      handleFilter,
      resetFilter,
      handleEdit,
      handleDelete,
      showExport,
      showDetailsDialog,
      showEditDialog,
      showPaymentDialog,
      showGenerateDialog,
      showDeleteDialog,
      showAddDialog,
      showImportDialog,
    };
  },
};
</script>

<style scoped>
.table-container {
  width: 100%;
}

.centered-buttons {
  display: flex;
  justify-content: center;
}
</style>